/*
 * @lc app=leetcode.cn id=904 lang=golang
 *
 * [904] 水果成篮
 */
package Solutions

// @lc code=start
func totalFruit(fruits []int) int {
	l := 0
	var valI = 0
	var nums = make([]int, len(fruits))
	for i := 1; i < len(fruits); i++ {
		if fruits[valI] == fruits[i] {
			continue
		}
		nums[l] = i - valI
		fruits[l] = fruits[valI]
		l++
		valI = i
	}
	fruits[l] = fruits[len(fruits)-1]
	nums[l] = len(fruits) - valI
	fruits = fruits[:l+1]
	nums = nums[:l+1]
	maxLen := 0
	var l1 int
	if len(fruits) <= 2 {
		for _, v := range nums {
			maxLen += v
		}
		return maxLen
	}
	maxLen = 0
	l1 = fruits[0]
	for i := 1; i < len(fruits); i++ {
		t := nums[i-1] + nums[i]
		j := i + 1
		for ; j < len(fruits); j++ {
			if fruits[j] == l1 || fruits[j] == fruits[i] {
				t += nums[j]
			} else {
				break
			}
		}
		if maxLen < t {
			maxLen = t
		}
		l1 = fruits[j-1]
		i = j - 1

	}
	return maxLen

}

// @lc code=end
